package com.yl.zqy.controller.sys;

import com.yl.zqy.common.CustomException;
import com.yl.zqy.common.Result;
import com.yl.zqy.constant.ZQYConstant;
import com.yl.zqy.entity.sys.SysUser;
import com.yl.zqy.enums.ResultCode;
import com.yl.zqy.service.sys.SysUserService;
import com.yl.zqy.vo.common.IPageVo;
import com.yl.zqy.vo.user.UserInstanceVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author liang.yu
 * @since 2024-03-24
 */
@RestController
@RequestMapping("/sysUser")
@Tag(name = "用户管理", description = "SysUserController")
@RequiredArgsConstructor
public class SysUserController {
    private final SysUserService userService;

    @GetMapping("/online")
    @Operation(summary = "获取在线用户信息", tags = "用户管理")
    public Result<List<SysUser>> getUserOnline(
            @Parameter(description = "页号") @RequestParam(value = "current", defaultValue = ZQYConstant.CURRENT) int current,
            @Parameter(description = "页大小") @RequestParam(value = "size", defaultValue = ZQYConstant.SIZE) int size) {
        return userService.getUserOnline(current, size);
    }

    @GetMapping("/getUserByPage")
    @Operation(summary = "获取用户信息列表", tags = "用户管理")
    public Result<IPageVo<SysUser>> getUserByPage(
            @Parameter(description = "页号") @RequestParam(value = "current", defaultValue = ZQYConstant.CURRENT) int current,
            @Parameter(description = "页大小") @RequestParam(value = "size", defaultValue = ZQYConstant.SIZE) int size,
            @Parameter(description = "部门ID") @RequestParam(value = "deptId", required = false) String deptId,
            @Parameter(description = "状态") @RequestParam(value = "status", required = false) String status,
            @Parameter(description = "条件查询（账号or姓名or手机号）") @RequestParam(value = "query", required = false) String query) {
        return userService.getUserByPage(current, size, deptId, status, query);
    }

    @PostMapping("/add")
    @Operation(summary = "新增用户信息", tags = "用户管理")
    public Result<Boolean> insertUser(@RequestBody UserInstanceVo user) {
        Optional.ofNullable(user.getUsername()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "用户名不能为空！"));
        return userService.insertUser(user);
    }

    @PutMapping("/update")
    @Operation(summary = "修改用户信息", tags = "用户管理")
    public Result<Boolean> updateUser(@RequestBody UserInstanceVo user) {
        Optional.ofNullable(user.getId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "用户ID不能为空！"));
        Optional.ofNullable(user.getUsername()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "用户名不能为空！"));

        return userService.updateUser(user);
    }

    @PutMapping("/updateByUserState")
    @Operation(summary = "修改用户状态（启用or停用）", tags = "用户管理")
    public Result<Boolean> updateByUserState(@RequestBody UserInstanceVo user) {
        Optional.ofNullable(user.getId()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "用户ID不能为空！"));
        Optional.ofNullable(user.getStatus()).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "用户状态不能为空！"));
        return userService.updateUser(user);
    }

    @DeleteMapping("/deleteById/{id}")
    @Operation(summary = "删除用户（根据ID）", tags = "用户管理")
    public Result<Boolean> deleteById(
            @Parameter(description = "id") @PathVariable(value = "id") String id) {
        Optional.ofNullable(id).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "用户ID不能为空！"));
        List<String> ids = new ArrayList<>();
        ids.add(id);
        return userService.deleteById(ids);
    }

    @DeleteMapping("/deleteByIds")
    @Operation(summary = "批量删除用户", tags = "用户管理")
    public Result<Boolean> deleteByIds(
            @Parameter(description = "ids集合") @RequestBody List<String> ids) {
        Optional.ofNullable(ids).orElseThrow(() -> new CustomException(ResultCode.PARAMS_ERROR, "用户ID不能为空！"));
        return userService.deleteById(ids);
    }

    @GetMapping("/exportDefaultUserTemplate")
    @Operation(summary = "下载用户导入模板", tags = "用户管理")
    public void exportDefaultUsers(HttpServletResponse response) {
        userService.exportDefaultUsers(response);
    }

    @PostMapping("/uploadUsers")
    @Operation(summary = "批量用户导入", tags = "用户管理")
    public Result<Boolean> uploadUsers(@Parameter(description = "file", content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE), required = true) @RequestParam("file") MultipartFile file) {
        return Result.ok(userService.uploadUsersRead(file));
    }
}
